<?php

/**
 * zhifubao.php
 * 支付宝小程序支付获取支付数据
 * Author: netman
 * DateTime:  2023/10/20 4:37
 */
class Service_Api_Payment_Zhifubao extends Contract_Api_Payment
{
    use Trait_Api_Common;
    use Trait_Api_Payment;

    /**
     * 获取支付数据
     * @param $params
     * @return array
     * @throws Exception
     * User: netman
     * Date: 2023/10/20 15:16
     */
    function get_pay_data($params): array
    {
        // 验证订单状态
        $order_sn = $params['ordersn'];

        // 验证订单
        $checkOrder = Model_Api_V2_Payment::ordersn_checked($order_sn);

        if ( ! $checkOrder['status']) {
            throw new $checkOrder['msg'];
        }

        $orderInfo = Model_Member_Order::order_info($order_sn);

        //"0元"订单,免费产品
        if ($orderInfo['pay_price'] == 0) {
            $zero_res = $this->zero_pay($order_sn);
            if ($zero_res['status']) {
                $orderInfo['sign'] = $zero_res['data']['sign'];
                return array(
                    'info' => $orderInfo,
                    'pay_method' => [],
                    'additional' => [],
                    'btn_title' => '查看订单'
                );
            } else {
                throw new Exception($zero_res['msg']);
            }
        }

        if ($orderInfo && $orderInfo['status'] == 1 && $orderInfo['memberid'] == $params['mid']) {
            //支付金额
            $totalprice = $orderInfo['payprice'];
            // 获取会员小程序openid
            $member_third = DB::select()->from("member_third")
                ->where("mid", "=", $params['mid'])
                ->execute()
                ->current();
            if ($member_third && $member_third['zfb_userid']) {
                $zfb_userid = $member_third['zfb_userid'];
                $params = array(
                    'order' => $order_sn,
                    'outTradeNo' => $order_sn.'_'.time(),
                    'totalprice' => sprintf('%.2f', $totalprice),
                    'order_title' => $orderInfo['productname'],
                    'user_id' => $zfb_userid,
                    'body' => $order_sn.'产品购买',
                );
                include BASEPATH.'plugins/api/classes/model/api/v2/payment/zhifubao.php';
                $status = Model_Api_V2_Payment_Zhifubao::pay($params);
                if ($status['status']) {
                    $data = array(
                        'trade_no' => $status['data']['trade_no'],
                        'ordersn' => $order_sn,
                        'notify_url' => $status['notify_url']
                    );
                    return $data;
                } else {
                    throw new Exception('获取失败');
                }
            } else {
                throw new Exception('会员信息有误');
            }
        } else {
            throw new Exception('订单信息有误');
        }
    }

}